import { checkAllCart, deleteCart, findCartList, getNewCartGoods, insertCart, mergeLocalCart, updateCart } from '@/api/cart'

//  购物车模块
export default {
  namespaced: true,
  state () {
    return {
      // 购物车商品列表
      list: []
    }
  },
  getters: {
    // 有效上商品列表
    validList (state) {
      return state.list.filter(item => item.stock > 0 && item.isEffective)
    },
    // 有效商品的总件数
    validToast (state, getters) {
      return getters.validList.reduce((p, c) => p + c.count, 0)
    },
    // 有效商品的总价格
    validAmount (state, getters) {
      return getters.validList.reduce((p, c) => p + c.count * 100 * c.nowPrice, 0) / 100
    },
    // 无效商品列表
    inValidList (state) {
      return state.list.filter(item => item.stock <= 0 || !item.isEffective)
    },
    // 已选商品列表
    selectList (state, getters) {
      return getters.validList.filter(item => item.selected)
    },
    // 已选商品总件数
    selectTotal (state, getters) {
      return getters.selectList.reduce((p, c) => p + c.count, 0)
    },
    // 已选商品总金额
    selectAmount (state, getters) {
      return getters.selectList.reduce((p, c) => p + c.count * 100 * c.nowPrice, 0) / 100
    },
    // 是否需要全选
    isCheckAll (state, getters) {
      return getters.validList.length !== 0 && getters.validList.length === getters.selectList.length
    }
  },
  mutations: {
    // 加入购物车
    insertCart (state, payLoad) {
      // 如果之前加入过找到下标
      const sameIndex = state.list.findIndex(goods => goods.skuId === payLoad.skuId)
      if (sameIndex !== -1) {
        // 找到了  取出之前的数量
        const count = state.list[sameIndex].count
        payLoad.count += count
        // 删除之前的商品
        state.list.splice(sameIndex, 1)
      }
      // 添加商品
      state.list.unshift(payLoad)
    },
    // 修改购物车
    updateCart (state, payLoad) {
      const updateCart = state.list.find(item => item.skuId === payLoad.skuId)
      for (const key in payLoad) {
        if (payLoad[key] !== undefined && payLoad[key] !== null && payLoad[key] !== '') {
          updateCart[key] = payLoad[key]
        }
      }
    },
    // 删除购物车
    deleteCart (state, skuId) {
      const index = state.list.findIndex(item => item.skuId === skuId)
      state.list.splice(index, 1)
    },
    // 设置购物车
    setCartList (state, payLoad) {
      state.list = payLoad
    }
  },
  actions: {
    // 合并购物车
    async merageCart (ctx) {
      const cartList = ctx.state.list.map(({ skuId, selected, count }) => {
        return { skuId, selected, count }
      })
      await mergeLocalCart(cartList)
      ctx.commit('setCartList', [])
    },
    // 修改规格
    updateCartSku (ctx, { newSku, oldSkuId }) {
      return new Promise((resolve, reject) => {
        if (ctx.rootState.user.profile.token) {
          // 已经登录
          // 1. 获取原先商品的数量
          const oldGoods = ctx.state.list.find(item => item.skuId === oldSkuId)
          // 2. 删除原先商品
          deleteCart([oldSkuId]).then(() => {
            return insertCart({ skuId: newSku.skuId, count: oldGoods.count })
          }).then(res => {
            return findCartList()
          }).then(res => {
            ctx.commit('setCartList', res.result)
            resolve()
          })
          // 4. 更新列表
        } else {
          // 未登录
          const oldGoods = ctx.state.list.find(item => item.skuId === oldSkuId)
          ctx.commit('deleteCart', oldSkuId)
          const { skuId, price: nowPrice, inventory: stock, specsText: attrsText } = newSku
          const newGoods = { ...oldGoods, skuId, nowPrice, stock, attrsText }
          ctx.commit('insertCart', newGoods)
          resolve()
        }
      })
    },
    // 批量删除
    batchDeleteCart (ctx, isClear) {
      return new Promise((resolve, reject) => {
        if (ctx.rootState.user.profile.token) {
          // 已经登录
          const selectedList = ctx.getters[isClear ? 'inValidList' : 'selectList'].map(item => item.skuId)
          deleteCart(selectedList).then(() => {
            return findCartList()
          }).then(res => {
            ctx.commit('setCartList', res.result)
          })
        } else {
          // 未登录
          ctx.getters[isClear ? 'inValidList' : 'selectList'].forEach(item => {
            ctx.commit('deleteCart', item.skuId)
          })
          resolve()
        }
      })
    },

    // 全选取消全选
    checkAllCart (ctx, selected) {
      return new Promise((resolve, reject) => {
        if (ctx.rootState.user.profile.token) {
          // 已经登录
          const ids = ctx.getters.validList.map(item => item.skuId)
          checkAllCart({ selected, ids }).then(() => {
            return findCartList()
          }).then(res => {
            ctx.commit('setCartList', res.result)
            resolve()
          })
        } else {
          // 未登录
          ctx.getters.validList.forEach(item => {
            ctx.commit('updateCart', { skuId: item.skuId, selected })
          })
          resolve()
        }
      })
    },
    // 修改购物车
    updateCart (ctx, payLoad) {
      return new Promise((resolve, reject) => {
        if (ctx.rootState.user.profile.token) {
          // 已经登录
          updateCart(payLoad).then(() => {
            return findCartList()
          }).then(res => {
            ctx.commit('setCartList', res.result)
            resolve()
          })
        } else {
          // 未登录
          ctx.commit('updateCart', payLoad)
          resolve()
        }
      })
    },
    // 加入购物车
    insertCart (ctx, payLoad) {
      return new Promise((resolve, reject) => {
        if (ctx.rootState.user.profile.token) {
          // 已经登录
          insertCart({ skuId: payLoad.skuId, count: payLoad.count }).then(res => {
            return findCartList()
          }).then(res => {
            ctx.commit('setCartList', res.result)
            resolve()
          })
        } else {
          // 未登录
          ctx.commit('insertCart', payLoad)
          resolve()
        }
      })
    },
    // 获取商品列表
    findCart (ctx) {
      return new Promise((resolve, reject) => {
        if (ctx.rootState.user.profile.token) {
          // 已经登录
          findCartList().then(res => {
            ctx.commit('setCartList', res.result)
            resolve()
          })
        } else {
          // 未登录
          const promiseArr = ctx.state.list.map(item => {
            return getNewCartGoods(item.skuId)
          })
          Promise.all(promiseArr).then(res => {
            res.forEach((item, index) => {
              ctx.commit('updateCart', { skuId: ctx.state.list[index].skuId, ...item.result })
            })
            resolve()
          })
        }
      })
    },
    // 删除购物车
    deleteCart (ctx, skuId) {
      return new Promise((resolve, reject) => {
        if (ctx.rootState.user.profile.token) {
          // 已经登录
          deleteCart([skuId]).then(res => {
            return findCartList()
          }).then(res => {
            ctx.commit('setCartList', res.result)
            resolve()
          })
        } else {
          // 未登录
          ctx.commit('deleteCart', skuId)
          resolve()
        }
      })
    }
  }
}
